package trees;

import java.util.*;
import java.util.stream.Collectors;

public class TopKFrequent {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> freqMap = new LinkedHashMap<>();
        List<Integer> val = Arrays.stream(nums).boxed().collect(Collectors.toList());
        int size = val.size();
        for (int i = 0; i < size; i++) {
            int freq = freqMap.getOrDefault(nums[i], 0);
            freq += 1;

            freqMap.put(nums[i], freq);
        }


        Map<Integer, Integer> sortMap = new LinkedHashMap<>();
        freqMap.entrySet().stream().sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue())).collect(Collectors.toList()).forEach(res -> sortMap.put(res.getKey(), res.getValue()));

        List<Integer> keys = new ArrayList<>(sortMap.keySet());
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            result.add(keys.get(i));
        }

        return result.stream().mapToInt(Integer::intValue).toArray();
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 1, 1, 2, 2, 3};
        int k = 2;

        TopKFrequent frequent = new TopKFrequent();
        Arrays.stream(frequent.topKFrequent(nums, k)).forEach(System.out::println);
    }
}
